import React, { Component, useRef, useEffect, useState } from "react";
import { Button, Input, Row, Space, Table, Tabs } from 'antd';
import { CmdbContent, CmdbHeader , TempImportModal, HcpTableTooltip, useModelAssociateType} from "@/components";
import cmdbres from "@/data/cmdbres";
import request from "@/utils/request";
import CreateRelation from "./createRelation";
import EditRelation from "./editRelation";
import DeleteRelation from "./deleteRelation";
import ModelTopology from "@/modules/topology/allModelTopology/topology";
import '../index.less'

const {TabPane} = Tabs;
const ModelRelations = ({ history}) => {
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState([]);
    const [showCreateRelation, setShowCreateRelation] = useState(false);
    const [showEditRelation, setShowEditRelation] = useState(false);
    const [showDeleteRelation, setShowDeleteRelation] = useState(false);
    const [showImportModal, setShowImportModal] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [{associateType}] = useModelAssociateType();

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryAllModelAssociate,
                data: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    sort: {
                        createTime:"DESC"
                    }
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total, 
                }));
                res.data.map((item, index) => item.key=index);
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        } 
    };

    useEffect(() => {
        getTableData();
    }, []);

    const handleTableChange = (e) => {
        getTableData(e);
    };
    
    const columns = [
        {
            title: "唯一标识",
            key: "moduleAssociateCode",
            dataIndex: "moduleAssociateCode",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "模型关系名称",
            key: "moduleAssociateName",
            dataIndex: "moduleAssociateName",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "源模型",
            key: "srcModuleName",
            dataIndex: "srcModuleName",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "目标模型",
            key: "destModuleName",
            dataIndex: "destModuleName",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "关联类型",
            key: "associateType",
            dataIndex: "associateType",
            isShow: true,
            width: 120,
            render: (text, record, index) => {
                return associateType?.[text] || text;
            }
        },
        {
            title: "源目标约束",
            key: "mapping",
            dataIndex: "mapping",
            isShow: true,
            width: 120,
        },
        {
            title: "关联描述",
            key: "description",
            dataIndex: "description",
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: "操作",
            fixed: 'right',
            width: 110,
            woIsSystem: 1,
            woIsHidden: 1,
            render: (text, record, index) => {
                return (
                <Space key={record.cm_unid}>
                    <a onClick={() => { setRow(record); setShowEditRelation(true); }}>修改</a>
                    <a onClick={() => { setRow(record); setShowDeleteRelation(true); }}>删除</a>
                </Space>
                )
            }
        } 
    ]

    const topologyRef = useRef();
    const [activeKey, setActiveKey] = useState("list");
    const handleTabOnChange = (tab) => { 
        setActiveKey(tab);
    }

    return (
        <CmdbContent>
            <CmdbHeader title={"模型关系"} />
            <section className="hcp__page">
                <section className="hcp__page__container">
                    <div style={{backgroundColor: "#fff", padding: "10px"}}>
                    <div style={{ display: "inline-block", width: "50%" }}>
                        <section style={{float: "left", padding: "5px 10px 10px 0"}}>
                            <Space>
                                <Button type="primary" onClick={() => {setShowImportModal(true);}}>
                                    导入关联
                                </Button>
                                <Button type="primary" onClick={() => {setShowCreateRelation(true);}}>
                                    新建关联
                                </Button>
                                <Button type="primary" onClick={getTableData} >
                                    刷新
                                </Button>
                            </Space>
                        </section>
                    </div>
                    <Tabs 
                        defaultActiveKey={"list"} 
                        size="large" 
                        style={{ float: "right", padding: '5px 0px', margin: 0}}
                        onChange={handleTabOnChange}
                    >
                        <TabPane tab="列表" key="list"> </TabPane>
                        <TabPane tab="拓扑" key="topology"> </TabPane>
                    </Tabs>
                    <div style={{display: activeKey == 'list'? 'block': 'none'}}>
                        <Table
                            columns={columns}
                            loading={loading}
                            dataSource={tableData}
                            scroll={{ x: '100%' }}
                            pagination={{
                                showSizeChanger: true,
                                showQuickJumper: {
                                goButton: (
                                    <Button style={{ margin: "0 10px" }}>确定</Button>
                                ),
                                },
                                ...pagination,
                            }}
                            onChange={handleTableChange}
                            hideSetting
                        />
                    </div>
                    {/*必须要用visibility */}
                    <div style={{visibility: activeKey == 'topology'? 'visible': 'hidden'}}>
                        <ModelTopology history={history} visible={activeKey == 'topology'} cRef={topologyRef} />
                    </div>
                </div>
                </section>
            </section>
            {showCreateRelation&&<CreateRelation
                onCreateFinish={()=>{
                    getTableData();
                    topologyRef.current.onRefresh();
                }}
                visible={showCreateRelation}
                setVisible={setShowCreateRelation}
            />}
            {showEditRelation&&<EditRelation
                onCreateFinish={()=>{
                    getTableData();
                    topologyRef.current.onRefresh();
                }}
                visible={showEditRelation}
                setVisible={setShowEditRelation}
                info={row}
            />}
            <DeleteRelation
                onDeleteFinish={getTableData}
                visible={showDeleteRelation}
                setVisible={setShowDeleteRelation}
                info={row}
            />
            <TempImportModal
                visible={showImportModal}
                setVisible={setShowImportModal}
                onImportFinish={getTableData}
                downloadApi="模型关系.xlsx" // 下载模板
                downloadURL={'/module/export/export-associate-excel'} // 下载地址
                importApi={cmdbres.importModelAssociate} // 导入地址
            />
        </CmdbContent>
    );
};

export default ModelRelations;